#pragma once

#include "Framebuffer.h"
#include "RenderBuffer.h"
#include "Texture.h"

namespace Gut
{
	struct RenderTarget
	{
		FrameBuffer frameBuffer;
		std::vector<Texture2D> outColors;

		Texture2DDesc texDesc;

		Texture2D depthMap;
		Texture2DDesc depthDesc;

		RenderBuffer rBuffer;
		int mWidth, mHeight;

		struct Desc
		{
			int width, height;
			int numTexture;
			int format = GL_RGBA;
			int internalFormat = GL_RGBA;
			int dataType = GL_FLOAT;
			int target = GL_TEXTURE_2D;
		};
		void Create(const Desc &desc);

		void SetWindowSize(int width, int height);
		
		void Begin()
		{
			frameBuffer.Bind();
			glViewport(0, 0, mWidth, mHeight);
		}

		void End()
		{
			frameBuffer.UnBind();
		}

		struct ScreenShotDesc
		{
			int attachment = GL_COLOR_ATTACHMENT0;

			int x = 0;
			int y = 0;
			int width = 1;
			int height = 1;
			int format = GL_FLOAT;
			int type = GL_RGBA;
			void *out = 0;
		};

		void SceenShot(const ScreenShotDesc &desc)
		{
			frameBuffer.Bind();
			glReadBuffer(desc.attachment);
			glReadPixels(desc.x, desc.y, desc.width, desc.height, desc.format, desc.type, desc.out);
			frameBuffer.UnBind();
		}

		int ReadOneRGBA(float xa, float ya, int attachmentOffset)
		{
			unsigned char udata[4];

			Gut::RenderTarget::ScreenShotDesc desc;

			desc.attachment = GL_COLOR_ATTACHMENT0 + attachmentOffset;
			desc.width = 1;
			desc.height = 1;
			desc.x = xa * mWidth;
			desc.y = mHeight * ya;
			desc.out = udata;
			desc.format = GL_RGBA;
			desc.type = GL_UNSIGNED_BYTE;

			SceenShot(desc);


			unsigned r = udata[0];
			unsigned g = udata[1];
			unsigned b = udata[2];
			unsigned a = udata[3];

			int objectID = ((int)r << 24) | ((int)g << 16) | ((int)b << 8) | (int)a;
			return objectID;

		}
	};

}